/*
 * Copyright (c) 2006 Zsolt Szasz <zsolt at lorecraft dot com>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package org.lorecraft.routes;

import java.io.File;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.webwork.config.Configuration;
import com.opensymphony.webwork.dispatcher.mapper.ActionMapper;
import com.opensymphony.webwork.dispatcher.mapper.ActionMapping;

public abstract class RouteActionMapper implements ActionMapper {
	private RouteSet routeSet;

	public RouteActionMapper() {
		routeSet = buildRouteSet();
	}

	protected abstract RouteSet buildRouteSet();
	
	public ActionMapping getMapping(HttpServletRequest request) {
		if ("true".equalsIgnoreCase(Configuration.getString("webwork.configuration.xml.reload"))) {
			// for hotswap
			routeSet = buildRouteSet();
		}
		String uri = request.getServletPath();
		String includeUri = (String) request.getAttribute("javax.servlet.include.servlet_path");
		if (includeUri != null) {
			uri = includeUri;
		}
		if (!"/".equals(uri) && new File(request.getRealPath(uri)).exists()) {
			return null;
		}
		RouteMapping result = routeSet.map(uri);
		if (result == null) {
			return null;
		}		
		ActionMapping mapping = new ActionMapping();
		mapping.setName(result.getAction());
		mapping.setNamespace(result.getNamespace());
		mapping.setParams(result.getParams());
		return mapping;
	}

	public String getUriFromActionMapping(ActionMapping mapping) {
		final Map mappingParams = mapping.getParams();
		String[] params = Utils.convertToParameterArray(mappingParams);
		String path = routeSet.getPath(mapping.getNamespace(), mapping.getName(), params);
		mappingParams.clear();
		return path;
	}
}
